package com.cedifie.syc.data.http

import com.cedifie.http.OkHttp
import com.cedifie.http.callback.StringCallback
import com.cedifie.http.model.Response
import com.cedifie.syc.data.util.ASAesUtil
import org.json.JSONObject
import java.io.IOException
import java.util.function.Supplier

class ASPostAsyncTask(val url: String, val body: String, val taskId: String? = null) :
    Supplier<JSONObject> {

    override fun get(): JSONObject {
        return ASPostSyncTask(url = url, body = body, taskId = taskId).doPost()
    }
}

class ASPostSyncTask(val url: String, val body: String, val taskId: String? = null) {

    fun doPost(): JSONObject {
        try {
            if (this.url.isBlank() or this.body.isBlank()) return JSONObject().apply {
                put("taskId", taskId)
            }
            println(">>>>>device data toUrl:$url")
            println(">>>>>device data body:$body")
            println(">>>>>device data body aes:${ASAesUtil.decryptDefault(body)}")

            OkHttp.post<String>(url) // 请求方式和请求url
                .tag(this) // 请求的 tag, 主要用于取消对应的请求
                .upString(body)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        val body = response.body()
                        if (response.code() != 200 || body == null || body.isEmpty()){
                            println(">>>>>$url>>>device data errorCode： ${response.code()}, errorMsg: ${response.message()}")
                            return
                        }

                        val result = ASAesUtil.decryptDefault(body)
                        if (result.isNotEmpty()){
                            println(">>>>>$url>>>device data success : $result")
                        }
                    }

                    override fun onError(response: Response<String>) {
                        println(">>>>>$url>>>device data errorCode： ${response.code()}, errorMsg: ${response.message()}")
                    }
                    override fun onFinish() {
                    }
                })
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return JSONObject().apply {
            put("taskId", taskId)
        }
    }
}